package com.rtx.config.swagger;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.Arrays;
import java.util.List;

/**
 * swagger配置类
 * 访问地址：
 * 原生地址：http://IP:PORT/swagger-ui/index.html
 * bootstrap-ui地址：http://IP:PORT/doc.html
 */
@Configuration
@EnableOpenApi
public class SwaggerConfig {

    @Value("${swagger.enable:0}")
    private String enable;

    @Bean
    public Docket webApiConfig() {
        return new Docket(DocumentationType.OAS_30)
                .enable("1".equals(enable))
                .pathMapping("/")
                .groupName(Docket.DEFAULT_GROUP_NAME)
                .apiInfo(webApiInfo())
                .securityContexts(Arrays.asList(securityContext()))
                .securitySchemes(Arrays.asList(securitySchemes()))
                //设置哪些接口暴露给swagger展示
                .select()
                //扫描指定注解
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();

    }

    private SecurityScheme securitySchemes() {
        return new ApiKey("Authorization","Authorization","header");
    }

    private SecurityContext securityContext() {
        return SecurityContext.builder().securityReferences(deaultAuth()).build();
    }

    private List<SecurityReference> deaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global","全局");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return Arrays.asList(new SecurityReference("Authorization",authorizationScopes));
    }

    private ApiInfo webApiInfo() {
        return new ApiInfoBuilder()
                .title("API文档")
                .description("本文档描述了接口定义")
                .version("1.0")
                .build();
    }
}
